<?php

namespace app\common\business;

use app\admin\model\SystemConfig as modelObj;
use app\common\lib\Show;


class Shipping extends Base
{
    /**
     *
     */
    public function __construct()
    {
        $this->modelObj = new ModelObj();
    }

    /**
     *  获取配送费的设置
     * @return int[]
     */
    public function getConfigSet(){
        $shippings =array('shippingstartfee'=>0,'shippingstart'=>0,'shippingmore'=>0,'shippingmorefee'=>0,'shippingend'=>0,'shippingendfee'=>0);
        try{
            $shipping=$this->modelObj->where([['name','in',['shippingstart','shippingstartfee','shippingmore','shippingmorefee','shippingend','shippingendfee']]])->select()->toArray();
        }catch (\Exception $e){
            throw new Exception("查询失败");
        }

        if($shipping){
            foreach ($shipping as $k=>$v){
                switch ($v['name']){
                    case 'shippingstartfee': //起步价
                        $shippings['shippingstartfee'] =$v['value'];
                        break;
                    case 'shippingstart': // 含公里数
                        $shippings['shippingstart'] =$v['value'];
                        break;
                    case 'shippingmorefee':  // 续费每公里配送费
                        $shippings['shippingmorefee'] =$v['value'];
                        break;
                    case 'shippingmore':  // 续费公里
                        $shippings['shippingmore'] =$v['value'];
                        break;
                    case 'shippingend':  // 续费公里截止
                        $shippings['shippingend'] =$v['value'];
                        break;
                    case 'shippingendfee':  // 固定费用
                        $shippings['shippingendfee'] =$v['value'];
                        break;
                    default:
                        break;
                }
            }
        }
        return $shippings;
    }

    /**
     * 计算运费
     * @param $lng
     * @param $lat
     * @param $mlng
     * @param $mlat
     * @return float|int
     */
    public function sumshippingFee($lng,$lat,$mlng,$mlat){

        $shippingfee =0;
        $config=$this->getConfigSet();
        if($lng && $lat && $mlng && $mlat){
            // 相隔公里数
            $juli = Show::getShippingDistances($lng,$lat,$mlng,$mlat,2);
            // 小于等于起始距离
            if($juli<=$config['shippingstart']){
                $shippingfee =$config['shippingstartfee'];
            }elseif ($juli>$config['shippingstart'] && $juli<$config['shippingend']){
                $shippingfee =round($config['shippingstartfee']+ceil(($juli-$config['shippingstart'])/$config['shippingmore'])*$config['shippingmorefee'],2);
            }else if($juli >=$config['shippingend']){
                $shippingfee =$config['shippingendfee'];
            }
        }else{
            $shippingfee =$config['shippingstartfee'];
        }
        return $shippingfee;
    }
}